//index.js
import config from '../../config.js';
var util = require('../../utils/util.js');
const base = config;

//获取应用实例
const app = getApp();
Page({
  data: {
    showLocationTip: false,
    isFirstOpen: true,
    //车辆列表
    carList: [],
    mainInfo: {
      star: []
    },
    msg: {
      title: '温馨提示',
      content: ''
    },
    // banner轮播
    swiper: {
      autoplay: true,
      indicatorDots: true,
      url: 'http://www.baidu.com',
    },

    // 事故提示
    tips: {
      autoplay: true,
      indicatorDots: false,
      vertical: true,
      circular: true,
      list: []
    },

    // 功能列表
    funList: [{
        icon: "https://app.longchg.com/gudongcar/images/chexian.png",
        text: "车险报价",
        url: "../insurance/insurance"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/shiguxiezhu.png",
        text: "事故协助",
        url: "../accidentAssi/accidentAssi"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/weizhangbanli.png",
        text: "违章办理",
        url: "../peccancy/step2"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/daiweixiu.png",
        text: "代维修",
        url: "../repair/repair"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/daibaoyang.png",
        text: "代保养",
        url: "../maintenance/maintenance"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/member.png",
        text: "菇咚会员",
        url: "../member/activation"
      },
      {
        icon: "https://app.longchg.com/gudongcar/images/jiesongji.png",
        text: "接送机",
        url: "../airport/airport"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/daibuche.png",
        text: "代步车",
        url: "../stepcar/stepcar"
      },
      {
        icon: "https://app.longchg.com/gudongcar/images/dainianjian.png",
        text: "代年检",
        url: "../yearaudit/yearaudit"
      }, {
        icon: "https://app.longchg.com/gudongcar/images/jiuyuan.png",
        text: "菇咚金融",
        url: "../finance/loanPlan"
        //url: "../rescure/rescure"
      },
      /** {
         icon: "https://app.longchg.com/gudongcar/images/gengduo.png",
         text: "其他",
         url: "../others/others"
       }**/
    ],

    // 我的管家
    manager: {
      header: "../../image/default.png",
      name: "张伟",
      score: "9.0",
      level: 4.5,
      adept: "汽车挂牌；车辆保养、维修；续保、保险理赔等",
      detail: "../managerDetail/managerDetail",
    },
    show: false,
    message: []
  },

  //删除车辆
  deleteCar: function(e) {
    var instance = this;
    wx.showModal({
      title: "温馨提示",
      content: "是否确认删除车辆信息？",
      showCancel: true,
      confirmColor: "#137AF0",
      success: function(er) {
        console.log(er);
        if (er.confirm) {
          let id = e.currentTarget.dataset.id,
            index = e.currentTarget.dataset.index,
            that = this;
          wx.showLoading({
            title: '正在删除',
          })
          wx.request({
            url: base.carDelete,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': wx.getStorageSync("session")
            },
            data: {
              id: id
            },
            success: function(res) {
              wx.hideLoading();
              console.log(res);
              if (res.data.status == 200) {
                wx.showToast({
                  title: '删除成功',
                })
                instance.getCarList();
              } else {
                wx.showToast({
                  title: "删除失败",
                  icon: "none"
                })
              }
            }
          })
        }
      }
    })


  },



  //违章查询
  illegalQuery: function(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../peccancyList/peccancyList?id=' + id,
    })
  },

  onLoad: function() {
    this.loadData();
    this.loadNoPay();
  },
  loadNoPay: function() {
    //请求管家列表
    var that = this;
    wx.request({
      url: base.orderNoPay,
      header: {
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: 1
      },
      method: "POST",
      success: function(res) {
        console.log(res.data.data);
        if (res.data.data.length > 0) {
          wx.setTabBarBadge({
            index: 2,
            text: res.data.data.length + "",
          })
          if (!that.data.show) {
            wx.showModal({
              title: '温馨提示',
              content: '您有待支付订单需要支付费用，请及时查看',
              success(re) {
                if (re.confirm) {
                  console.log('用户点击确定')
                  console.log(res.data.data)
                  wx.navigateTo({
                    url: '../orderDetail/orderDetail?id=' + res.data.data[0],
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }


        }
      }
    })
  },
  loadData: function() {
    //请求管家列表
    var that = this;
    wx.request({
      url: base.mainInfo,
      header: {
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: 1
      },
      method: "POST",
      success: function(res) {
        console.log("首页信息");
        console.log(res.data.data);
        var mainInfo = res.data.data.keeper;
        var star = [];
        for (var i = 0; i < mainInfo.score; i++) {
          star.push(i);
        }
        that.setData({
          mainInfo: res.data.data,
          'mainInfo.star': star,
          "tips.list": res.data.data.newList,
          funList: res.data.data.menus


        })


        wx.setStorageSync("MyDefaultHouseKeeper", mainInfo);
        wx.setStorageSync("services", that.data.mainInfo.services);
        wx.setStorageSync("isAddCar", that.data.mainInfo.isAddCar);


      }
    })

    if (that.data.isFirstOpen) {
      //判断会员权益
      var user = wx.getStorageSync("user");
      console.log(user);
      if (user.isMemberShip == 1) {
        this.setData({
          show: false
        })
      } else {
        this.setData({
          show: true
        })
      }

      that.setData({
        isFirstOpen: false
      })

    }

  },
  getCarList: function() {
    var that = this;
    //请求车辆列表
    wx.request({
      url: base.myCarsList,
      header: {
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        start: 0
      },
      success: function(res) {
        console.log(res);
        if (res.data.status == 200) {
          that.setData({
            carList: res.data.data
          })
          if (that.data.carList == null || that.data.carList.length == 0) {
            wx.setStorageSync("isAddCar", null);
          }

        }
      }
    })
  },
  tipBannerDetail: function(e) {
    var url = e.currentTarget.dataset.url;
    wx.setStorageSync("webviewUrl", url);
    wx.navigateTo({
      url: "../webview/webview"
    })
  },
  tipDetail: function(e) {
    var item = e.currentTarget.dataset.item;
    wx.setStorageSync("webviewUrl", item.url);
    wx.navigateTo({
      url: "../webview/webview"
    })
  },
  onShow: function() {
    var that = this;
    var houseKeeper = wx.getStorageSync("MyDefaultHouseKeeper");
    if (houseKeeper) {
      var star = [];
      for (var i = 0; i < houseKeeper.score; i++) {
        if (i <= 4) {
          star.push(i);

        } else {
          break;
        }
      }
      var flag = util.checkLocationIsOff(this);
      console.log(flag);

      this.setData({
        "mainInfo.keeper": houseKeeper,
        "mainInfo.star": star,
        showLocationTip: flag
      })

      that.loadOffData();

      that.loadData();
    }



    this.getCarList();
    setTimeout(this.addListener, 1000);
  },
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.loadNoPay();
    wx.stopPullDownRefresh();
    wx.hideNavigationBarLoading() //完成停止加载
  },
  carDetailAction: function(e) {
    console.log(e);
    var carId = e.currentTarget.dataset.carid;
    wx.navigateTo({
      url: '../mine/minecar/carDetail?id=' + carId,
    })
  },
  funAction: function(e) {
    var url = e.currentTarget.dataset.url;
    var isAddCar = wx.getStorageSync("isAddCar");
    if (!isAddCar) {
      if (url == "../member/activation" || url == "../finance/loanPlan") {
        wx.navigateTo({
          url: url,
        })
        return;
      }
      wx.showModal({
        title: "温馨提示",
        content: "您还未添加车辆，请先添加车辆",
        showCancel: true,
        confirmColor: "#137AF0",
        success: function(e) {
          console.log(e);
          if (e.confirm) {
            wx.navigateTo({
              url: '../addCar/addCar',
            })
          }
        }
      })
    } else {
      if (url != '') {
        wx.navigateTo({
          url: url,
        })
      }
    }

  },
  onReady: function() {

  },
  closeHandler: function() {
    this.setData({
      show: false
    })
  },
  activeAction: function() {
    wx.navigateTo({
      url: '../member/activation',
    })
  },
  bindAction: function() {
    wx.scanCode({
      scanType: ['scanType', 'qrCode', 'datamatrix', 'pdf417'],
      success: function(res) {
        console.log(res);
        wx.navigateTo({
          url: '../member/confirm?id=' + res.result,
        })
      }
    })
  },
  contactAction: function() {
    var that = this;
    //请求车辆列表
    wx.request({
      url: base.defaultKeeperAccount,
      header: {
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        start: 0
      },
      success: function(res) {
        console.log(res);
        if (res.data.status == 200) {
          wx.setStorageSync("keeperAccount", res.data.data);
          wx.setStorageSync("MyDefaultHouseKeeper", res.data.data.housekeeper);
          wx.navigateTo({
            url: '../msg/chat?type=2',
          })

        } else {
          wx.showToast({
            title: '即时通讯信息获取失败',
            icon: 'none'
          })
        }
      }
    })

  },
  handler: function(e) {
    if (e.detail.authSetting["scope.userLocation"]) { //如果打开了地理位置，就会为true
      this.setData({
        showLocationTip: true
      })
    }
  },
  addListener: function() {
    var that = this;
    console.log("添加监听");
    app.globalData.callback = function(res) {
      console.log('收到服务器内容2：' + res.data)
      //解析消息 
      var json = JSON.parse(res.data);
      if (json.ntitle != null) {
        wx.showModal({
          title: json.ntitle,
          content: json.ncontent,
          success(e) {
            if (e.confirm) {
              if (json.isRead == "0") {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.switchTab({
                  url: '../order/order',
                })
              } else {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.navigateTo({
                  url: '../gjorder/gjorder',
                })
              }

            }
          }
        })
        wx.setTabBarBadge({
          'index': 2,
          text: '1'
        })
      } else {
        var msg = that.data.message;
        msg.push(json);
        that.setData({
          message: msg,
        })

        wx.showTabBarRedDot({
          index: 1,
        })
      }
    }
  },
  chatMessageAction: function(e) {
    var that = this;
    var data = that.data.message[that.data.message.length - 1];
    wx.setStorageSync("chatUser", data);
    wx.navigateTo({
      url: '../msg/chat',
    })

    that.setData({
      message: []
    })

  },
  loadOffData: function() {
    var that = this;
    //即时通讯
    wx.request({
      url: base.chatOffLineMessageList,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": wx.getStorageSync("session")
      },
      data: {
        start: 0,
        size: 10,
      },
      success: function(res) {
        console.log(res);
        if (res.statusCode == 200) {
          if (res.data.data.length == 0) {

            that.setData({
              message: []
            })
          }
        }
      }
    })
  },
})